﻿using AspNet.Identity.Dapper.Db;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AspNet.Identity.Dapper
{
    public class UserRolesTable
    {
        private readonly DbManager _db;
        public UserRolesTable(DbManager dbManager)
        {
            this._db = dbManager;
        }

        public List<string> FindByUserId(Guid userId)
        {
            return _db.Connection.Query<string>("Select Role.Name from UserRole, Role where UserRole.UserId=@UserId and UserRole.RoleId = Role.Id", new { userId = userId.ToString() })
                .ToList();
        }

        /// <summary>
        /// Deletes all roles from a user in the UserRoles table
        /// </summary>
        /// <param name="userId">The user's id</param>
        /// <returns></returns>
        public bool Delete(Guid userId)
        {
            return _db.Connection.Execute(@"Delete from UserRole where Id = @userId", new { userId=userId.ToString() })>0;
        }

        /// <summary>
        /// Inserts a new role for a user in the UserRoles table
        /// </summary>
        /// <param name="user">The User</param>
        /// <param name="roleId">The Role's id</param>
        /// <returns></returns>
        public bool Insert(IdentityUser user, Guid roleId)
        {
             return _db.Connection.Execute(@"Insert into UserRole (UserId, RoleId) values (@userId, @roleId",
                new { userId = user.Id.ToString(), roleId= roleId.ToString()})>0;
        }
    }
}
